<template>
  <el-card class="index-container">
    <template #header>
      <div class="header">
        <div class="search-container">
          <el-input
              v-model="state.searchValue"
              placeholder="服务名称关键字"
              clearable
              style="width: 200px; margin-right: 10px"
          />
          <el-button type="success" color="#71c4ef" @click="handleSearch">查询</el-button>
          <el-button type="success" color="#313d44" plain @click="handleReset">重置</el-button>
        </div>
        <div class="action-buttons">
          <el-button type="primary" color="#FF3D3D" :icon="Plus" @click="handleAdd">预约服务增加</el-button>
          <el-popconfirm
              title="确定删除吗？"
              confirmButtonText='确定'
              cancelButtonText='取消'
              @confirm="handleDelete"
          >
          </el-popconfirm>
        </div>
      </div>
    </template>

    <el-table
        :load="state.loading"
        ref="multipleTable"
        :data="state.tableData"
        tooltip-effect="dark"
        style="width: 100%"
        @selection-change="handleSelectionChange">
      <el-table-column
          type="selection"
          width="55">
      </el-table-column>
      <el-table-column
          label="序号"
          align="center"
          width="60"
      >
        <template #default="scope">
          {{ (state.currentPage - 1) * state.pageSize + scope.$index + 1 }}
        </template>
      </el-table-column>

      <el-table-column
          prop="name"
          label="服务名称"
          align="center"
      >
      </el-table-column>

      <el-table-column
          label="封面"
          align="center"
      >
        <template #default="scope">
          <img :src="scope.row.cover" alt="图片" style="width: 80px; height: 80px; border-radius: 12px;object-fit: cover;">
        </template>
      </el-table-column>

      <el-table-column
          label="类型"
          align="center"
      >
        <template #default="scope">
          <div style="display: flex; align-items: center; justify-content: center;">
            <el-icon :style="{ marginRight: '4px', color: getServiceTypeColor(scope.row.serviceType) }">
              <component :is="getServiceTypeIcon(scope.row.serviceType)" />
            </el-icon>
            <span>{{ scope.row.serviceType }}</span>
          </div>
        </template>
      </el-table-column>


      <el-table-column
          prop="description"
          label="描述"
          align="center"
      >
      </el-table-column>


      <el-table-column label="操作" width="200" align="center">
        <template #default="scope">
          <div class="action-buttons">
            <!-- 编辑按钮 -->
            <el-button
                type="warning"
                size="small"
                :icon="Edit"
                :disabled="scope.row.id === '1'"
                @click="handleEdit(scope.row.id)">
              编辑
            </el-button>

            <!-- 删除按钮（带确认） -->
            <el-popconfirm
                title="确定要删除此项吗？"
                confirm-button-text="确认"
                cancel-button-text="取消"
                @confirm="handleDeleteOne(scope.row.id)"
            >
              <template #reference>
                <el-button
                    type="danger"
                    size="small"
                    :icon="Delete"
                    :disabled="scope.row.id === '1'"
                    style="margin-left: 8px">
                  删除
                </el-button>
              </template>
            </el-popconfirm>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <!--总数超过一页，再展示分页器-->
    <el-pagination
        v-if="state.total > state.pageSize"
        background
        layout="prev, pager, next"
        :total="state.total"
        :page-size="state.pageSize"
        :current-page="state.currentPage"
        @@size-change="handleSizeChange"
        @current-change="changePage"
    />
  </el-card>
  <!--  编辑弹窗控件-->
  <addElderlyService ref='infoClassify' :reload="getIndexConfig" :type=state.type
                     :configType="state.configType"/>
</template>

<script setup>
import {onMounted, reactive, ref, toRefs} from 'vue'
import {ElMessage} from 'element-plus'
import addElderlyService from '../../components/ServicePensionDialog.vue'
import {useRoute, useRouter} from 'vue-router'
import {Check, Delete, Edit, House, Message, OfficeBuilding, Search, Star,} from '@element-plus/icons-vue'
import {listElderlyServices,deleteElderlyServiceById } from '../../service/elderlyServiceApi.js'

// 首页配置类型参数
const configTypeMap = {
  hot: 3,
  new: 4,
  recommend: 5
}

const router = useRouter()
const route = useRoute()
const multipleTable = ref(null)
const infoClassify = ref(null)
const state = reactive({
  searchValue: '', // 新增搜索值
  loading: false,
  tableData: [], // 数据列表
  multipleSelection: [], // 选中项
  total: 0, // 总条数
  currentPage: 1, // 当前页
  pageSize: 5, // 分页大小
  type: 'add', // 操作类型
  configType: 3 // 3-(首页)热销商品 4-(首页)新品上线 5-(首页)为你推荐
})

// 监听路由变化
router.beforeEach((to) => {
  if (['hot', 'new', 'recommend'].includes(to.name)) {
    state.configType = configTypeMap[to.name]
    state.currentPage = 1
    getIndexConfig()
  }
})

// 初始化
onMounted(() => {
  state.configType = configTypeMap[route.name]
  getIndexConfig()
})

// 获取列表数据（添加搜索参数）
const getIndexConfig = async () => {
  state.loading = true
  const params = {
    pageNum: state.currentPage,
    pageSize: state.pageSize,
    keyWord: state.searchValue
  }
  // 查询资讯分类列表数据
  const response = await listElderlyServices(params);
  state.tableData = response.data.records || []
  state.total = response.data.total || 0
}

const getServiceTypeIcon = (serviceType) => {
  return serviceType === '上门服务' ? House : OfficeBuilding;
};

const getServiceTypeColor = (serviceType) => {
  return serviceType === '上门服务' ? '#67C23A' : '#409EFF'; // 绿色或蓝色
};
// 搜索处理
const handleSearch = () => {
  state.currentPage = 1
  getIndexConfig()
}

// 重置处理
const handleReset = () => {
  state.searchValue = ''
  getIndexConfig()
}

// 其他原有方法保持不变...
// 添加商品
const handleAdd = () => {
  state.type = 'add'
  infoClassify.value.open()
}

// 修改商品
const handleEdit = (id) => {
  console.log('handleEdit', id)
  state.type = 'edit'
  infoClassify.value.open(id)
}

// 选择项
const handleSelectionChange = (val) => {
  state.multipleSelection = val
}

// 单个删除
const handleDeleteOne = (id) => {
  // 原有删除逻辑...
  deleteElderlyServiceById(id).then(() => {
    ElMessage.success('删除成功')
    getIndexConfig()
  })
}

// 分页处理
const changePage = (val) => {
  state.currentPage = val
  getIndexConfig()
}

// 每页条数变化
const handleSizeChange = (val) => {
  state.pageSize = val
  state.currentPage = 1
  getIndexConfig()
}
</script>

<style scoped>
.index-container {
  min-height: 100%;
}

.el-card.is-always-shadow {
  min-height: 100% !important;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-container {
  display: flex;
  align-items: center;
  flex: 1;
  margin-right: 20px;
}

.action-buttons {
  display: flex;
  gap: 10px;
}
</style>
